<?php

/**
 * 图片验证码生成
 * 
 * @copyright (c) 2008, fvzone All Rights Reserved
 * $Id: captcha.php 526 2008-07-05 15:21:03Z wang $
 */
class captcha
{
    //验证码回话前缀
    public $captcha_key = 'captcha_key';
    public static $instance;

	public static function singleton($captcha_key = null)
    {
		if (!self::$instance)
        {
			self::$instance = new self();
            $key = is_null($captcha_key) ? self::$instance->captcha_key : self::$instance->captcha_key.$captcha_key;
            self::$instance->captcha_key = sha1($key);
        }
		return self::$instance;
	}

    //显示验证码
	public function show($captcha_key = null)
	{
		header('Content-type:image/png');
		//创建图片
		$im = imagecreate(80, 30);
		//第一次对imagecolorallocate()的调用会给基于调色板的图像填充背景色
		$bg = imagecolorallocate($im, 255, 255, 255);
		//验证码使用字体
		$font_style = WORK_DIR."assets/milkcocoa.ttf";
		//字符
		$text_char = 'BCEFGHJKMPQRTVWXY2346789';
		//字符间隔
		$text_spac = 16;
		//产生随机字符
		for($i = 0;$i < 4;$i++)
		{
			$font_color = imagecolorallocate($im, mt_rand(50, 200), mt_rand(0, 155), mt_rand(0, 155));
			$text_str = $text_char[mt_rand(0, 23)];
			imagettftext($im, 24, mt_rand(0, 20) - mt_rand(0, 25), 5 + $i * $text_spac, mt_rand(25, 30), $font_color, $font_style, $text_str);
			$auth_code .= $text_str;
		}
		
        //用户和用户输入验证码做比较
		$_SESSION[$this->captcha_key] = $auth_code;
        
		//干扰线
		/**
		 * for($i = 0;$i < 8;$i++)
		 * {
		 * $line_color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
		 * imageline($im, rand(0, 130), 0, rand(0, 130), 145, $linecolor);
		 * }
		 */
		//干扰点
		for($i = 0;$i < 250; $i++)
		{
			imagesetpixel($im, rand(0, 130), rand(0, 145), $font_color);
			imagesetpixel($im, rand(0, 130), rand(0, 145), $font_color);
		} 

		imagepng($im);
		imagedestroy($im);
	}

    public function check($value)
    {
        return isset($_SESSION[$this->captcha_key]) && $_SESSION[$this->captcha_key] === strtoupper($value) ? true : false;
    }
}
